import Vue from "vue";
import axios from "axios";
import store from "@/store";
import router from "@/router/index";
import api from "../api/index";
import Global from "../api/common/Global";
// import message from 'ant-design-vue/es/message'
import { VueAxios } from "./axios";
import { ACCESS_TOKEN } from "../store/mutation-types";

// 创建 axios 实例
const service = axios.create({
    baseURL: Global.ApiBaseUrl, // api base_url
    timeout: 60000 // 请求超时时间
});

let error5001 = 0;

let networkError = false;

let LOADING = true;//防连点处理
let isLoading = false;

// 请求拦截器
service.interceptors.request.use(config => {
    const token = Vue.ls.get(ACCESS_TOKEN);
    if (token) {
        config.headers[ACCESS_TOKEN] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    if (config.isLoading) {
        isLoading = config.isLoading;
        if (LOADING) {
            LOADING = false;
        } else {
            return false;
        }
    }
    return config;
}, error => {
    if (error.request) {
        if (error.request.readyState == 4 && error.request.status == 0) {
            //我在这里重新请求
            console.log("请求超时：");
        }
    }
    return Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use(response => {
    //更新token
    const token = response.headers[ACCESS_TOKEN.toLowerCase()];
    if (token) {
        console.log(new Date().toLocaleTimeString(),"---更新token---:", token)
        Vue.ls.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000);
        store.commit("SET_TOKEN", token);
    }
    if (response.config.url == api.Login) {
        return response;
    }
    if (isLoading) {
        isLoading = false;
        if (!LOADING) {
            LOADING = true;
        } else {
            LOADING = false;
        }
    }
    if (!response.data.size  && response.data.code != 200) {
        if (response.data.code == '5001' && error5001 == 0) {
            error5001 = 1;

            let isHaveRight = store.getters.permissions.includes("system:accountsetting");
            let message = "请联系管理员进行‘账套配置’";
            let okText = "确定";
            let cancelText = "关闭";
            if (isHaveRight) {
                message = "没有账套数据,请配置账套";
                okText = "马上配置";
                cancelText = "稍后配置";
            }
            if (window.location.pathname != '/finance/setting/accountSetting') {
                antd.Modal.info({
                    title: '提示',
                    content: message,
                    okText,
                    cancelText,
                    onOk () {
                        if (isHaveRight) {
                            window.location.replace("/finance/setting/accountSetting");
                        }
                    },
                    onCancel () {
                        console.log("没有账套数据，" + cancelText)
                    },
                });
            }
            return false;
        } else {
            if (response.data.message != null && response.data.message && response.data.code != 5002) {
                antd.message.info({
                    content: response.data.message,
                })
            }
            return response.data;
        }
        return ;
    }
    return response.data;
}, error => {
    console.log("response------------ 请求时错误-----------error：",error);
    //响应
    if (error.response) {
        const { data, config } = error.response;
        const token = Vue.ls.get(ACCESS_TOKEN);
        if (config.url == api.Login) {
            return Promise.reject(error);
        }
        if (error.response.status === 400 || (error.response.status > 401 && error.response.status < 601)) {
            if (error.response.data.code != 5001) {
                antd.message.error({
                    content: data.message,
                })
            }
        }
        if (error.response.status === 500) {
            // if (error.response.data.code == '5001' && error5001 == 0) {
            //     error5001 = 1;

            //     let isHaveRight = store.getters.permissions.includes("system:accountsetting");
            //     let message = "请联系管理员进行‘账套配置’";
            //     let okText = "确定";
            //     let cancelText = "关闭";
            //     if (isHaveRight) {
            //         message = "没有账套数据,请配置账套";
            //         okText = "马上配置";
            //         cancelText = "稍后配置";
            //     }
            //     if (window.location.pathname != '/finance/setting/accountSetting') {
            //         antd.Modal.info({
            //             title: '提示',
            //             content: message,
            //             okText,
            //             cancelText,
            //             onOk () {
            //                 if (isHaveRight) {
            //                     window.location.replace("/finance/setting/accountSetting");
            //                 }
            //             },
            //             onCancel () {
            //                 console.log("没有账套数据，" + cancelText)
            //             },
            //         });
            // }

            // }
        }
        if (
            error.response.status === 401 &&
            !(data.result && data.result.isLogin)
        ) {
            store.dispatch("Logout").then(() => {
                router.push({ path: "login" });
            });
        }
    }else if (error.message.includes('timeout')) {
        if(!networkError){
            networkError = true;
            antd.message.error({
                content: "请求超时，请检测网络",
                duration:5
            })
            setTimeout(()=>{networkError = false},10000);
        }
        
    }else if(error.message.includes('Network Error')){
        if(!networkError){
            networkError = true;
            antd.message.error({
                content: "请求超时，请检测网络",
                duration:5
            })
            setTimeout(()=>{networkError = false},10000);
        }
    }
      
    return Promise.reject(error);
});

const installer = {
    vm: {},
    install (Vue) {
        Vue.use(VueAxios, service);
    }
};

export { installer as VueAxios, service as axios };
